package com.telit.uav.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.telit.common.entity.DataReturn;
import com.telit.common.entity.PageData;
import com.telit.common.enums.ResultCode;
import com.telit.uav.dto.CommUavReportInfoDTO;
import com.telit.uav.dto.UpdateUavLanAndLonDTO;
import com.telit.uav.entity.*;
import com.telit.uav.service.AppCruiseTrackService;
import com.telit.uav.service.CommUavReportInfoService;
import com.telit.uav.service.UavManagerService;
import com.telit.uav.service.UavQueryService;
import com.telit.uav.vo.CommUavModelVO;
import com.telit.uav.vo.UavDeviceProducterVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;


/**
 * @author zhouyu
 * @description 无人机管理接口
 */

@Api(tags = "01-无人机管理接口", description = "/uav-manager")
@RestController
@RequestMapping("/uav-manager")
public class UavManagerController {

    @Autowired
    private UavManagerService uavManagerService;

    @Autowired
    private UavQueryService uavQueryService;

    @Autowired
    private AppCruiseTrackService appCruiseTrackService;

    @Autowired
    private CommUavReportInfoService commUavReportInfoService;

    //添加无人机设备厂商
    @ApiOperation("01-添加无人机设备厂商")
    @PostMapping(value = "/addUavDeviceProducter", produces = "application/json;charset=UTF-8")
    public DataReturn<Long> addUavDeviceProducter(@RequestBody @Validated CommUavProducter commUavProducter) {
        Long id = uavManagerService.addUavDeviceProducter(commUavProducter);
        return DataReturn.ok(id);
    }


    @ApiOperation("02--分页查询无人机设备厂商")
    @GetMapping("/listDeviceProducterByPage")
    public DataReturn listDeviceProducterByPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name) {

        IPage<UavDeviceProducterVO> uavIPage = uavQueryService.listDeviceProducterByPage(current, size, name);
        return DataReturn.ok(new PageData<>((int) uavIPage.getTotal(), current, size, uavIPage));
    }

    //删除设备厂商

    @ApiOperation("03--删除设备厂商")
    @GetMapping("/deleteDeviceProducter")
    public DataReturn deleteDeviceProducter(@RequestParam(required = true) Long id) {
        uavQueryService.deleteDeviceProducter(id);
        return DataReturn.ok("成功");
    }

    //添加无人机设备型号
    @ApiOperation("04---添加无人机设备型号")
    @PostMapping(value = "/addUavDeviceModel", produces = "application/json;charset=UTF-8")
    public DataReturn<Long> addUavDeviceModel(@RequestBody CommUavModel commUavModel) {
        Long id = uavManagerService.addUavDeviceModel(commUavModel);
        return DataReturn.ok(id);

    }

    @ApiOperation("05--分页查询无人机设备型号")
    @GetMapping("/listDeviceModelByPage")
    public DataReturn<List<CommUavModelVO>> listDeviceModelByPage(
            @RequestParam(required = false) String name) {
        List<CommUavModelVO> commUavModelVOS = uavQueryService.listDeviceModel(name);
        return DataReturn.ok(commUavModelVOS);
    }

    //删除无人机型号
    @ApiOperation("06-删除无人机设备型号")
    @GetMapping(value = "/deleteUavDeviceModel", produces = "application/json;charset=UTF-8")
    public DataReturn deleteUavDeviceModel(@RequestParam Long id) {
        uavManagerService.deleteUavDeviceModel(id);
        return DataReturn.ok("成功");
    }

    @ApiOperation("07-添加无人机设备")
    @PostMapping("/addUavDevice")
    public DataReturn addUavDevice(@RequestBody CommUav commUav) {
        if (commUav == null) {
            return DataReturn.failure(ResultCode.FORM_PARAMS_CHECK_ERROR);
        }
        uavManagerService.addUavDevice(commUav);
        return DataReturn.ok("添加无人机设备成功");
    }

    @GetMapping("/deleteById")
    @ApiOperation("删除无人机设备")
    public DataReturn deleteById(@RequestParam Long id) {
        try {
            if (id == null) {
                return DataReturn.failure(ResultCode.FORM_PARAMS_CHECK_ERROR);
            }
            uavManagerService.deleteById(id);
            return DataReturn.ok("删除无人机设备");
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure();
        }
    }

    @PostMapping(value = "/updateById", produces = "application/json;charset=UTF-8")
    @ApiOperation("修改无人机设备")
    public DataReturn updateById(@RequestBody CommUav commUav) {
        try {
            if (commUav == null) {
                return DataReturn.failure(ResultCode.FORM_PARAMS_CHECK_ERROR);
            }
            uavManagerService.updateById(commUav);
            return DataReturn.ok("修改无人机设备");
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure();
        }
    }

    //2022-08-29调整无人机离线状态
//    @ApiOperation("01--app端调用,修改无人机在离线状态")
//    @GetMapping("/changeUavStatus")
//    public DataReturn changeUavStatus(@RequestParam String uavCode,@RequestParam Long forestkeeperId,@RequestParam Integer isConnect){
//        try {
//            if (uavCode==null||forestkeeperId==null||isConnect==null){
//                return DataReturn.failure(ResultCode.REQUEST_PARAMS_CHECK_ERROR);
//            }
//            uavManagerService.changeStatus(uavCode,forestkeeperId,isConnect);
//            String token = uavQueryService.queryTokenByUavCode(uavCode);
//            return DataReturn.ok(token);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return DataReturn.failure(ResultCode.SERVER_ERROR);
//        }
//    }


    @GetMapping("/changeStatus")
    @ApiOperation("08--app端调用,修改无人机在离线状态")
    public DataReturn changeStatus(@RequestParam(value = "uavCode", required = false) String uavCode,
                                   @RequestParam(value = "forestkeeperId", required = false) Long forestkeeperId,
                                   @RequestParam(value = "isConnect", required = false) Integer isConnect,
                                   @RequestParam(value = "longitude", required = false) String longitude,
                                   @RequestParam(value = "latitude", required = false) String latitude
    ) {
        try {
            if (uavCode == null || forestkeeperId == null || isConnect == null) {
                return DataReturn.failure(ResultCode.REQUEST_PARAMS_CHECK_ERROR);
            }
            uavManagerService.changeStatus(uavCode, forestkeeperId, isConnect, longitude, latitude);
            String token = uavQueryService.queryTokenByUavCode(uavCode);
            return DataReturn.ok(token);
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.SERVER_ERROR);
        }
    }


    @GetMapping(value = "/listUavProducter", produces = "application/json;charset=UTF-8")
    @ApiOperation("09--查询所有无人机设备厂商")
    public DataReturn listUavProducter() {
        return DataReturn.ok(uavQueryService.listUavProducter());
    }

    @GetMapping(value = "/getUavModelByProId", produces = "application/json;charset=UTF-8")
    @ApiOperation("10---根据设备厂家Id查询无人机型号")
    public DataReturn getUavModelByProId(@RequestParam Long ProducterId) {
        return DataReturn.ok(uavQueryService.getUavModelByProId(ProducterId));
    }

    @GetMapping("/startOrEndPatrol")
    @ApiOperation("app端调用,开始结束巡护 startOrEnd 1 开始巡护 2结束巡护")
    public DataReturn startOrEndPatrol(@RequestParam String uavCode, @RequestParam String startOrEnd,
                                       @RequestParam(required = false) String trackId) {
        try {
            if (uavCode == null) {
                return DataReturn.failure(ResultCode.REQUEST_PARAMS_CHECK_ERROR);
            }
            uavManagerService.startOrEndPatrol(uavCode, startOrEnd, trackId);
            return DataReturn.ok("开始或结束巡护成功");
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.SERVER_ERROR);
        }
    }

    @PostMapping("/uploadCruiseTrack")
    @ApiOperation("无人机上传轨迹")
    public DataReturn uploadCruiseTrack(@RequestBody AppCruiseTrack appCruiseTrack){
        try {
            if (appCruiseTrack==null){
                return DataReturn.failure(ResultCode.FORM_PARAMS_CHECK_ERROR);
            }
            appCruiseTrackService.uploadCruiseTrack(appCruiseTrack);
            return DataReturn.ok("上传轨迹成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure();
        }
    }



    @GetMapping("/queryByName")
    @ApiOperation("根据健康状态和名称查询无人机列表（健康状态，0是正常，1是损坏 ，2是报废）")
    public DataReturn queryByStatusAndName(@RequestParam(required = false) Integer healthStatus,@RequestParam(required = false) String name){
        try {
            List<CommUav> commUavs=uavManagerService.queryByHealthStatusAndName(healthStatus,name);
            return DataReturn.ok(commUavs);
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.OPERATE_ERROR,"查询失败！");
        }
    }

/*    @PostMapping("/uploadRealTimeTrack")
    @ApiOperation("无人机上传实时轨迹")
    public DataReturn uploadRealTimeTrack(@RequestBody AppUavTrackDetail appUavTrackDetail){
        try {
            if (appUavTrackDetail==null){
                return DataReturn.failure(ResultCode.FORM_PARAMS_CHECK_ERROR);
            }
            appUavTrackDetailService.uploadRealTimeTrack(appUavTrackDetail);
            return DataReturn.ok("无人机上传实时轨迹");
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure();
        }
    }*/

    @GetMapping("/modifyIsFlying")
    @ApiOperation("app端调用,修改无人机是否飞行中")
    public DataReturn modifyIsFlying(@NotNull(message = "无人机编号不能为空") String uavCode,@NotNull(message = "是否飞行中不能为空") Integer isFlying){
        try {
            uavManagerService.modifyIsFlying(uavCode,isFlying);
            return DataReturn.ok("更新是否飞行中成功");
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.SERVER_ERROR,"更新是否飞行中失败");
        }
    }

    @PostMapping(value = "/report", produces = "application/json;charset=UTF-8")
    @ApiOperation("上报故障和上报维修,给飞手app端使用(上报故障：1 （1：损坏 2：报废））（ 上报维修：2)" )
    public DataReturn add(@RequestBody @Validated CommUavReportInfo commUavReportInfo, @RequestParam(value = "files", required = false) List<MultipartFile> files) {
        if (!CollectionUtils.isEmpty(files)) {
            List<String> imgList = new ArrayList<>();
            for (MultipartFile file : files) {
                // 调用minio-server接口传入图片
                //TODO:v1.1.0
//                imgList.add(MinioUtils.upload(file, MinioConstants.BUCKET_FORESTRY_NAME, MinioConstants.BUCKET_UAV_SUFFIX_NAME));
            }
            commUavReportInfo.setFileUrl(JSONObject.toJSONString(imgList));
        }
        commUavReportInfoService.add(commUavReportInfo);
        return DataReturn.ok();
    }
    @GetMapping("/reportList")
    @ApiOperation("查询无人机故障维修上报记录")
    public DataReturn queryReportList(@ModelAttribute CommUavReportInfoDTO commUavReportInfoDTO){
        try {
            IPage<CommUavReportInfo> commUavs = uavManagerService.queryReportList(commUavReportInfoDTO);
            return DataReturn.ok(commUavs);
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.OPERATE_ERROR, "查询失败！");
        }
    }


    @PostMapping("/updateUavLonAndLan")
    @ApiOperation("修改无人机经纬度")
    public DataReturn updateUavLonAndLan(@RequestBody UpdateUavLanAndLonDTO updateUavLanAndLonDTO) {
        uavManagerService.updateUavLonAndLan(updateUavLanAndLonDTO);
        return DataReturn.ok("修改经纬度成功");
    }

}
